package main

import (
	"flag"
	"fmt"
	"github.com/atotto/clipboard"
	"github.com/gen2brain/beeep"
	"github.com/minio/minio-go"
	"github.com/tucnak/store"
	"log"
	"os"
	"path"
	"time"
)

const (
	ConfigDir  = "minio-uploader"
	ConfigFile = "config.yml"
)

type Config struct {
	Endpoint        string
	AccessKeyID     string
	SecretAccessKey string
	UseSSL          bool
	BucketName      string
	Location        string
	Format          string
}

func init() {
	// You must init store with some truly unique path first!
	store.Init(ConfigDir)
}

func main() {
	defer func() { // 必须要先声明defer，否则不能捕获到panic异常
		if err := recover(); err != nil {
			fmt.Println(fmt.Errorf("先请执行 %s -config-template 生成配置模板，并编辑~/.config/%s/%s", path.Base(os.Args[0]), ConfigDir, ConfigFile)) // 这里的err其实就是panic传入的内容
		}
	}()
	template := flag.Bool("config-template", false, "generate a empty config template file")
	flag.Parse()
	var config Config
	// 生成空配置文件
	if *template {
		config.Format = "2006-01"
		if err := store.Save(ConfigFile, &config); err != nil {
			log.Println("failed to save the cat hotel:", err)
			return
		}
		return
	}
	// 加载配置文件
	if err := store.Load(ConfigFile, &config); err != nil {
		log.Println("failed to load the cat config:", err)
		return
	}
	if config.Endpoint == "" {
		fmt.Println("请先填写配置文件。")
		return
	}

	// Initialize minio client object.
	minioClient, err := minio.New(config.Endpoint, config.AccessKeyID, config.SecretAccessKey, config.UseSSL)
	if err != nil {
		log.Fatalln(err)
	}

	// Make a new bucket called mymusic.
	err = minioClient.MakeBucket(config.BucketName, config.Location)
	if err != nil {
		// Check to see if we already own this bucket (which happens if you run this twice)
		exists, errBucketExists := minioClient.BucketExists(config.BucketName)
		if errBucketExists == nil && exists {
			log.Printf("We already own %s\n", config.BucketName)
		} else {
			log.Fatalln(err)
		}
	} else {
		log.Printf("Successfully created %s\n", config.BucketName)
	}

	// Upload the zip file

	objectName := fmt.Sprintf("%s/%s", time.Now().Format(config.Format), path.Base(os.Args[1]))

	// Upload the zip file with FPutObject
	n, err := minioClient.FPutObject(config.BucketName, objectName, os.Args[1], minio.PutObjectOptions{})

	if err != nil {
		log.Fatalln(err)
	}
	log.Printf("Successfully uploaded %s of size %d\n", objectName, n)
	schema := "http"
	if config.UseSSL {
		schema = "https"
	}
	url := fmt.Sprintf("%s://%s/%s/%s", schema, config.Endpoint, config.BucketName, objectName)
	err = beeep.Notify("MinIO Uploader", fmt.Sprintf("文件上传成功: %s", url), "MinIOUploader.jpg")
	if err != nil {
		fmt.Println(err)
	}
	err = clipboard.WriteAll(url)
	if err != nil {
		fmt.Println(err)
	}
}
